package com.triumphxx.readingreminderbackend.service;

import com.triumphxx.readingreminderbackend.entity.ReviewSchedule;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author:triumphxx
 * @Date: 2025/11/26
 * @Time: 14:43
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: 邮件发送服务
 **/
@Service
@Slf4j
public class SendMailService {


    @Autowired
    private JavaMailSender mailSender;

    // 从配置文件中读取发件人邮箱
    @Value("${spring.mail.username}")
    private String fromEmail;

    // 从配置文件中读取收件人邮箱，如果没有配置则使用发件人邮箱
    @Value("${app.reminder.to-email:${spring.mail.username}}")
    private String toEmail;

    // 日期格式化
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    public void sendEmailReminder(ReviewSchedule review) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject("📚 复习提醒: " + review.getNote().getTitle());

            String emailContent = buildEmailContent(review);
            helper.setText(emailContent, true); // true表示内容是HTML格式

            mailSender.send(message);
            log.info("邮件提醒发送成功: {}", review.getNote().getTitle());
        } catch (Exception e) {
            log.error("发送邮件提醒失败: {}", review.getNote().getTitle(), e);
            System.err.println("邮件发送失败: " + e.getMessage());
        }
    }

    public void sendSummaryEmail(List<ReviewSchedule> reviews) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(fromEmail);
            helper.setTo(toEmail);
            helper.setSubject("📊 今日复习任务汇总 - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            String summaryContent = buildSummaryContent(reviews);
            helper.setText(summaryContent, true); // true表示内容是HTML格式

            mailSender.send(message);
            log.info("汇总邮件发送成功，共 {} 条复习任务", reviews.size());
        } catch (Exception e) {
            log.error("发送汇总邮件失败", e);
            System.err.println("汇总邮件发送失败: " + e.getMessage());
        }
    }

    private String buildEmailContent(ReviewSchedule review) {
        return String.format(
                "<!DOCTYPE html>" +
                        "<html>" +
                        "<head>" +
                        "    <meta charset=\"UTF-8\">" +
                        "    <style>" +
                        "        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }" +
                        "        .container { max-width: 600px; margin: 0 auto; padding: 20px; }" +
                        "        .header { background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%); color: white; padding: 20px; border-radius: 10px 10px 0 0; }" +
                        "        .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 10px 10px; }" +
                        "        .note-title { font-size: 18px; font-weight: bold; color: #2c3e50; }" +
                        "        .link { color: #3498db; text-decoration: none; font-weight: bold; }" +
                        "        .link:hover { color: #2980b9; text-decoration: underline; }" +
                        "        .stage { background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; }" +
                        "        .footer { margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }" +
                        "    </style>" +
                        "</head>" +
                        "<body>" +
                        "    <div class=\"container\">" +
                        "        <div class=\"header\">" +
                        "            <h2>📖 复习提醒</h2>" +
                        "        </div>" +
                        "        <div class=\"content\">" +
                        "            <p><strong>笔记标题:</strong> <span class=\"note-title\">%s</span></p>" +
                        "            <p><strong>复习阶段:</strong> <span class=\"stage\">第 %d 次复习</span></p>" +
                        "            <p><strong>语雀链接:</strong> <a href=\"%s\" class=\"link\" target=\"_blank\">点击查看笔记</a></p>" +
                        "            <p><strong>语雀链接:</strong> %s</p>" +
                        "            <p><strong>提醒时间:</strong> %s</p>" +
                        "            <br>" +
                        "            <p>请及时复习，巩固知识！💪</p>" +
                        "        </div>" +
                        "        <div class=\"footer\">" +
                        "            <p>来自您的阅读提醒系统</p>" +
                        "        </div>" +
                        "    </div>" +
                        "</body>" +
                        "</html>",
                review.getNote().getTitle(),
                review.getStage(),
                review.getNote().getYuqueUrl(),
                review.getNote().getYuqueUrl(),
                LocalDateTime.now().format(formatter)
        );
    }

    private String buildSummaryContent(List<ReviewSchedule> reviews) {
        StringBuilder content = new StringBuilder();
        content.append("<!DOCTYPE html>")
                .append("<html>")
                .append("<head>")
                .append("    <meta charset=\"UTF-8\">")
                .append("    <style>")
                .append("        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }")
                .append("        .container { max-width: 600px; margin: 0 auto; padding: 20px; }")
                .append("        .header { background: linear-gradient(135deg, #f093fb 0%%, #f5576c 100%%); color: white; padding: 20px; border-radius: 10px 10px 0 0; }")
                .append("        .content { background: #f9f9f9; padding: 20px; border-radius: 0 0 10px 10px; }")
                .append("        .note-item { background: white; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #3498db; }")
                .append("        .note-title { font-weight: bold; color: #2c3e50; }")
                .append("        .link { color: #3498db; text-decoration: none; }")
                .append("        .link:hover { color: #2980b9; text-decoration: underline; }")
                .append("        .stage { background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; margin-left: 10px; }")
                .append("        .footer { margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }")
                .append("        .count { font-size: 16px; font-weight: bold; color: #e74c3c; }")
                .append("    </style>")
                .append("</head>")
                .append("<body>")
                .append("    <div class=\"container\">")
                .append("        <div class=\"header\">")
                .append("            <h2>📊 今日复习任务汇总</h2>")
                .append("        </div>")
                .append("        <div class=\"content\">")
                .append("            <p>总计需要复习的笔记: <span class=\"count\">").append(reviews.size()).append("</span> 条</p>")
                .append("            <br>");

        for (int i = 0; i < reviews.size(); i++) {
            ReviewSchedule review = reviews.get(i);
            content.append("            <div class=\"note-item\">")
                    .append("                <p><span class=\"note-title\">").append(i + 1).append(". ").append(review.getNote().getTitle())
                    .append("</span><span class=\"stage\">第").append(review.getStage()).append("次复习</span></p>")
                    .append("                <p><a href=\"").append(review.getNote().getYuqueUrl()).append("\" class=\"link\" target=\"_blank\">点击查看笔记</a></p>")
                    .append("</span><span class=\"stage\">语雀链接：").append(review.getNote().getYuqueUrl())
                    .append("            </div>");
        }

        content.append("            <br>")
                .append("            <p><strong>汇总时间:</strong> ").append(LocalDateTime.now().format(formatter)).append("</p>")
                .append("            <p>祝您复习愉快！🎯</p>")
                .append("        </div>")
                .append("        <div class=\"footer\">")
                .append("            <p>来自您的阅读提醒系统</p>")
                .append("        </div>")
                .append("    </div>")
                .append("</body>")
                .append("</html>");

        return content.toString();
    }

}
